<?php
namespace control;
/*
*质检方案
*/

class quarantineClass extends adIndexClass
{
    private const page = 'quarantine';
    private const table = 'quarantine';
    private const title = '质检方案';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "方案编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'description' => [
                        'name'  => "方案描述",
                        'width' => 200,
                    ],
                    'list'  => [
                        'name'  => "优先级",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'application'  => [
                        'name'  => '用途',
                        'width' => 220,
                    ],
                    'materialType'  => [
                        'name'  => '物料分类',
                        'width' => 150,
                    ],
                    'name'         => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'startDate'          => [
                        'name'  => '生效日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'endDate'          => [
                        'name'  => '失效日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function quarantineListOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "方案编号" => text(array("name" => "orderNo")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "方案描述"   => text(array("name" => "description")),
                    '物料分类' => selectMultiple(array("name" => "materialTypeId", "table" => "material_type", 'sqlField' => 'name', 'sqlId' => 'id')),
                ],
                [
                    '生效日期'  => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(array("name" => "state", "option" =>['启用','停用'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 物料-质检方案
     *
     * @return bool|string
     */
    public function quarantineList(): bool|string
    {
        $html = $this->quarantineListOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function quarantineListSearch(): bool|string
    {
        $materialId = $this->post('targetId');
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "description" => $this->post('description'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "materialId" => $materialId,
            "coid" =>self::$coid,
        );
        $and = "";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and startDate >='{$timeArr[0]}' and startDate <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $materialType = query('material_type',"id = '$array[materialTypeId]'");
            $material = query('material',"id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'materialType':
                        $row[] = $materialType['name'];
                        break;
                    case 'name':
                        $row[] = $material['name']?:'全部';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='quarantineListForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "方案编号" => text(array("name" => "orderNo")),
                    "方案描述"   => text(array("name" => "description")),
                    '物料分类' => selectMultiple(array("name" => "materialTypeId", "table" => "material_type", 'sqlField' => 'name', 'sqlId' => 'id')),
                ],
                [
                    '生效日期'  => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(array("name" => "state", "option" =>['启用','停用'])),
                ]
            ]
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('新建" . self::title . "','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>启用</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>停用</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "description" => $this->post('description'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "materialTypeId" => $this->post('materialTypeId'),
            "coid" =>self::$coid,
        );
        $and = "";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and startDate >='{$timeArr[0]}' and startDate <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $materialType = query('material_type',"id = '$array[materialTypeId]'");
            $material = query('material',"id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'materialType':
                        $row[] = $materialType['name'];
                        break;
                    case 'name':
                        $row[] = $material['name']?:'全部';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?:suiji();
        $info = query(self::table, " id = '" . $id. "' ");

        /*****质检项目*********/
        $educationTr[] = ['', '质检项', '检验标准', '结果选项（多个时中文逗号隔开）'];
        $result = find(array(
            'field' => "id as itemId,name as itemName,standard,result",
            'table' => self::table."_item"." where orderId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $educationTr[] = $this->itemRow($array);
            }
        }else{
            $educationTr[] = $this->itemRow(['mxId'=>self::getId(), 'list'=>1]);
        }

        /*****不良原因*********/
        $workTr[] = ['', '不良原因', '不良等级', '处理方式'];
        $result = find(array(
            'field' => "id as reasonId,reason,level,method",
            'table' => self::table."_reason"." where orderId = '{$info['id']}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $workTr[] = $this->reasonRow($array);
            }
        }else{
            $workTr[] = $this->reasonRow(['mxId'=>self::getId(), 'list'=>1]);
        }

        //按钮
	    $button[]  = [
		    "name"  => L('public.save'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		    "post"  => ["id" => $id],
		    'style' => 'li-btn-blue-bg',
	    ];
        $materialType = query('material_type',"id = '$info[materialTypeId]'");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '详细信息' => [
                [
                    must . "方案描述：" => text(["name" => "description", "value" => $info['description']]),
                    must ."优先级：" => text(["name" => "list", "value" => $info['list']]),
                    must . "用途：" => checkbox(["name" => "application", 'value' => ['来料检验', '制终检验','发货检验','委外入库检验'], "checked" => explode(',',$info['application'])]),
                ],
                [
                    must . "产品分类：" => "<input type='hidden' value='{$info['materialTypeId']}' name='materialTypeId'><span id='materialType'>{$materialType['name']}</span><span class='del-row-button' onclick=\"layer('".self::page."','materialType',{id:'".$info['materialTypeId']."'})\" style='margin-left: 10px'>选择</span>",
                    "产品名称：" =>  "<span id='material' class='full'>".
                        componentClass::selectText([
                            'name'      => 'materialId',
                            'value'     => $info['materialId'],
                            'title' => materialClass::getName($info['materialId']),
                            'cla'       => 'quarantine',
                            'fun'       => 'getMaterialList',
                            'param'    => "{'typeId':'".$info['materialTypeId']."'}",
                        ]).
                        "</span>",
                    must . "生效日期：" => text(["name" => "startDate",'laydate' => [], "value" => $info['startDate']]),
                    must ."失效日期：" => text(["name" => "endDate", 'laydate' => [], "value" => $info['endDate']]),
                ],
                [
                    "质检批量：" => text(["name" => "qualityBatch", "value" => $info['qualityBatch']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ],
            '检验标准' => [
                [
                    must ."质检方式：" => radio(["name" => "qualityType", 'value' =>['抽检','全检'], "checked" => $info['qualityType']]),
                    "抽检比例：" => text(["name" => "proportion", 'unit'=>'%',"value" => (float)$info['proportion']*100]),
                ],
                [
                    "检验要求：" =>  textarea(["name" => "mandate", "value" => $info['mandate']])
                ],
                [
                    "附件：" => fileUploadClass::addFileComponent($info['id'],'质检方案',self::page,self::page.'EditForm'),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => '质检项目',
            'html' => $this->listTable(array('tr' => $educationTr, 'end' => true)),
        ]);
        $body .= $this->editList([
            'title' => '不良原因',
            'html' => $this->listTable(array('tr' => $workTr, 'end' => true)),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
        ]);
        $data['html'] .= <<<efo
        <script>
                 //添加一行
                 function addRow(e,type){
                     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                        $(e).closest('tr').after(res.data);
                        resetNumber($(e).closest('tbody'))
                     },'json');
                 }
                 //选择分类
                 function chooseMaterialType(e){
                     let id = $(e).data('id');
                     let val = $(e).data('name');
                     $("#materialType").html(val);
                     $("[name='materialTypeId']").val(id);
                     $('#quarantineMaterialType').hide();
                     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getMaterial',{id:id},function (res){
                         $("#material").html(res.html)
                     },'json')
                 }
        </script>
efo;
        //返回
        return $this->tab($data);
    }

    /**
     * 模糊查询产品列表
     *
     * @return bool|string
     */
    public function getMaterialList(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $typeId          = $this->post('typeId');
        $json['warn'] = 0;
        $json['data'] = [];

        $where            = " coid = '" . self::$coid . "' ";
        $like             = [
            'name' => $val,
            'typePath' => $typeId,
        ];
        $equal            = [
        ];
        $where            .= search([
            "like" => $like,
            "="    => $equal,
        ]);
        $page = $this->page(array(
            'field' => 'name,id',
            "table" => 'material',
            "where" => $where,
            "order" => ' code ',
        ));
        $json['pageAll'] = $page['para']['pageAll'];
        $json['sql'] = $page['sql'];

        foreach ($page['array'] as $val) {
            $json['data'][] = [
                'title'   => $val['name'],
                'id'      => $val['id'],
            ];
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option['click'] = "replaceDetail($(this).parent(),'" . self::page . "')";
        $json['html'] = self::getDepartmentAll($option);
        return json_encode($json, 320);
    }

    /**
     * 获取产品选项
     */
    public function getMaterial(){
        $json['html'] = componentClass::selectText([
            'name'      => 'materialId',
            'value'     => '',
            'title' => '',
            'cla'       => 'quarantine',
            'fun'       => 'getMaterialList',
            'param'    => "{'typeId':'".$this->post('id')."'}",
        ]);
        return json_encode($json,320);
    }


    public static function getDepartmentAll($data = []): string
    {
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail($(this).parent(),'" . self::page . "')";
        // 结果
        $result = find(['table' => 'material_type', 'where' => $data['where'] . " and coid = '".self::$coid."' order by list asc"]);
        $style = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp = "<ul {$style} {$data['where']}>";
        if ($result['array']) {
            foreach ($result['array'] as $value) {
                // 角标
                $arrow = "<span class='arrow'  onclick=\"{$data['click']}\"></span>";
                // 判断下级是否存在
                $data['where'] = " pid='{$value['id']}' ";
                $has = query('material_type', $data['where']);
                if ($has['id']) {
                    $temp .= "<li class='arrow-li' data-id='{$value['id']}' data-name='{$value['name']}'  ondblclick='chooseMaterialType(this)' >{$arrow}<span class='textcontent' title='双击选择'><span class='textcontent_ico'></span>{$value['name']}</span></li>";
                    $temp .= self::getDepartmentAll($data);
                } else {
                    $temp .= "<li class='arrow-no-li'  data-id='{$value['id']}' data-name='{$value['name']}' ondblclick='chooseMaterialType(this)' onclick=\"{$data['click']}\"><span class='textcontent' title='双击选择'><span class='textcontent_ico'></span>{$value['name']}</span></li>";
                }
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 选择分类
     */
    public function materialType(): bool|string
    {
        $all = self::getDepartmentAll();
        $search          = "<div class='container-left-search-parent flex-box'>
                                ".text(["name" => 'name', 'title' => "搜索分类", 'class' => 'container-left-search','other' => " onkeyup='search_left(this,event)' "])."
                                <i class='container-left-search-ico' onclick=\"search_left(document.getElementsByClassName('container-left-search')[0])\"></i>
                                <span class='search-count'></span>
                            </div>";
        $html = <<<efo
                <div class="layer-container-main">
                    <div class="container-left paper-content-block" id="container-left">
                        {$search}
                        <div class="classify-area">
                        {$all}
                        </div>
                    </div>
                </div>
efo;

        return $this->layer(array("title" => "选择分类", "height" => 600, "width" => 800, "html" => $html, "button" => false));
    }


    /**
     * Desc : 质检项目
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function itemRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['itemId'])&&$data['itemId']?$data['itemId']:self::getId();
        $field = ['itemName', 'standard', 'result'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'itemRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'item')"),
            hidden(array('name' => 'itemId[]', 'value' => $mxId)) .
            text(array('name' => 'itemName[]', 'value' => $array['itemName'])),
            text(array('name' => 'standard[]', 'value' => $array['standard'])),
            text(array('name' => 'result[]', 'value' => $array['result']))
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * Desc : 不良原因
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function reasonRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['reasonId'])&&$data['reasonId']?$data['reasonId']:self::getId();
        $field = ['reason', 'level', 'method'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'reasonRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'reason')"),
            hidden(array('name' => 'reasonId[]', 'value' => $mxId)) .
            text(array('name' => 'reason[]', 'value' => $array['reason'])),
            text(array('name' => 'level[]', 'value' => $array['level'])),
            select(array('name' => 'method[]','title'=>'请选择','option'=>explode('，',para('dealMethod')), 'value' => $array['method']))
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $type = $this->post('type');
        $html = '';
        switch ($type) {
            case 'item':
                $res = json_decode($this->itemRow(),true);
                $html = $res['html'];
                break;
            case 'reason':
                $res = json_decode($this->reasonRow(),true);
                $html = $res['html'];
                break;
        }
        $json['data'] = $html;
        return json_encode($json, 320);
    }


    /**
     * 编辑保存
     * @return bool|string
     */
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'description' => $this->post('description'),
            'application' => $this->post('application')?implode(',',$this->post('application')):'',
            'materialTypeId' => $this->post('materialTypeId'),
            'materialId' => $this->post('materialId'),
            'startDate' => $this->post('startDate'),
            'endDate' => $this->post('endDate'),
            'list' => $this->post('list'),
            'qualityBatch' => $this->post('qualityBatch'),
            'text' => $this->post('text'),
            'qualityType' => $this->post('qualityType'),
            'proportion' => (float)$this->post('proportion')/100,
            'mandate' => $this->post('mandate'),
        ];
        $annotation = [
            'description' => '方案描述',
            'application' => '用途',
            'materialTypeId' => '产品分类',
            'startDate' => '生效日期',
            'endDate' => '失效日期',
            'list' => '优先级',
        ];
        $rules = [
            'description' => 'required',
            'application' => 'required',
            'materialTypeId' => 'required',
            'startDate' => 'required',
            'endDate' => 'required',
            'list' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();

        //质检项目
        $itemIdArr = $this->post('itemId') ?? [];
        $itemNameArr = $this->post('itemName');
        $standardArr = $this->post('standard');
        $resultArr = $this->post('result');
        //不良原因
        $reasonIdArr = $this->post('reasonId') ?? [];
        $reasonArr = $this->post('reason');
        $levelArr = $this->post('level');
        $methodArr = $this->post('method');
        //附件
        $fileIdArr = $this->post('fileId');

        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }elseif(static::is_null_array($itemIdArr)){
            $json['warn'] = '请添加质检项目';
        } elseif(static::is_null_array($itemNameArr)){
            $json['warn'] = '质检项不能留空';
        } elseif(static::is_null_array($reasonIdArr)){
            $json['warn'] = '请添加不良原因';
        } elseif(static::is_null_array($reasonArr)){
            $json['warn'] = '不良原因不能留空';
        } elseif(strtotime($field['startDate']) >= strtotime($field['endDate'])){
            $json['warn'] = '失效日期必须大于生效日期';
        }else {
            $this->startTrans();//开启事务
            $isPass = true;//事务通过标志
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'BOM' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'state' => '启用',
                    'orderNo'=>$userNo,
                    'coid' => self::$coid,
                    'stid'=>self::$stid,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            //添加或更新质检选项
            if (is_array($itemIdArr)) {
                foreach ($itemIdArr as $k => $nid) {
                    $mx = query(self::table.'_item',"id = '$nid'");
                    if (!empty($mx['id'])){
                        //更新
                        $warn = static::update([
                            "table" => self::table.'_item',
                            "field" => [
                                'name' => $itemNameArr[$k],
                                'standard' => $standardArr[$k],
                                'result' => $resultArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    }else {
                        //新增
                        $warn = static::insert([
                            "table" => self::table.'_item',
                            "field" => [
                                'id' => $nid,
                                'orderId' => $id,
                                'coid' => self::$coid,
                                'name' => $itemNameArr[$k],
                                'standard' => $standardArr[$k],
                                'result' => $resultArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新不良原因
            if (is_array($reasonIdArr)) {
                foreach ($reasonIdArr as $k => $nid) {
                    $mx = query(self::table.'_reason',"id = '$nid'");
                    if ($mx['id']) {
                        //更新
                        $warn = static::update([
                            "table" => self::table.'_reason',
                            "field" => [
                                'reason' => $reasonArr[$k],
                                'level' => $levelArr[$k],
                                'method' => $methodArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::table.'_reason',
                            "field" => [
                                'id' => $nid,
                                'orderId' => $id,
                                'coid' => self::$coid,
                                'reason' => $reasonArr[$k],
                                'level' => $levelArr[$k],
                                'method' => $methodArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                    $isPass = false;
                }
            }
            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务

                //删除不在此ID中的数据
                delete(array('table' => self::table.'_item', 'where' => " id not in ('" . implode("','", $itemIdArr) . "') and orderId = '$id' "));
                delete(array('table' => self::table.'_reason', 'where' => " id not in ('" . implode("','", $reasonIdArr) . "') and orderId = '$id'"));

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑",
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                        'style' => 'li-btn-blue-bg',
                    ];

                $state = $info['state'] == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $state,
                    "type" => "点击事件",
                    'title' => '修改状态',
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$state}'})",
                ];
                }
            if ($this->power(self::page, "del")) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($info['id'], '质检方案');

            $tr[] = ['质检项', '检验标准', '结果选项'];
            $result = find(array('table' => self::table."_item", 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $tr[] = [
                    $array['name'],
                    $array['standard'],
                    $array['result'],
                ];
            }
            $reasonTr[] = ['不良原因', '不良等级', '处理方式'];
            $result = find(array('table' => self::table."_reason", 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $reasonTr[] = [
                    $array['reason'],
                    $array['level'],
                    $array['method'],
                ];
            }
            $materialType = query('material_type',"id = '$info[materialTypeId]'");
            $material = query('material',"id = '$info[materialId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "方案描述" => $info['description'],
                        "优先级" => $info['list'],
                        "用途" => $info['application'],
                        "物料分类" => $materialType['name'],
                    ),
                    array(
                        "物料名称" => $material['name']?:'全部',
                        "生效日期" => $info['startDate'],
                        "失效日期" => $info['endDate'],
                    ),
                    array(
                        '备注'=>pre($info['text'])
                    )
                ),
                "检验标准" => array(
                    array(
                        "质检方式" => $info['qualityType'],
                        "抽检比例" => ((float)$info['proportion']*100).'%',
                        "质检批量" => $info['qualityBatch'],
                    ),
                    array(
                        "检验要求"=> pre($info['mandate']),
                    )
                ),
                "附件" => array(
                    array(
                        $fileCollection
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '质检项目',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '不良原因',
                'html' => $this->listTable(array('tr' => $reasonTr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            $data['html'] .= $this->tableShow(array(
                '系统信息'=>array(
                    [
                        "编号" => $info['orderNo'],
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ],
                    [
                        "状态" =>$info['state']
                    ],
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '启用') {
                    $warn = "删除失败：启用中";
                } else {
                    //删除不良原因
                    delete(array("table" => self::table.'_reason', "where" => " orderId = '$id' "));
                    //删除质检项目
                    delete(array("table" => self::table.'_item', "where" => " orderId = '$id' "));
                    $all = find(array('table' =>"file", "where"=>"targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                    }
                    //删除附件
                    delete(array("table" => 'file', "where" => " targetId = '$id' "));

                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        return json_encode($json, 320);
    }
    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                foreach ($idArr as $id) {
                    auditingFollow(array(
                        "type" => "bom",
                        "typeId" => $id,
                        "text" => "【{$this->control['name']}】" . $state,
                    ));
                }

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }


}
